package com.db4o.servlet;

import javax.servlet.*;
import javax.servlet.http.*;

import com.db4o.*;

/**
 * 
 * db4o servlet interface.
 * <br><br>This class is not part of db4o.jar. It is delivered as sourcecode in the path
 * ../com/db4o/servlet/<br><br>
 * <br>This class provides static methods to use db4o in a servlet environment. 
 * <br><br>The code takes care of all issues:
 * <br> - returning the same ObjectContaine instance for every call
 * with the same session parameter
 * <br> - closing the ObjectContainer upon session termination
 * <br> - closing the ObjectContainer upon shutdown
 * <br> - closing and reopening the ObjectContainer in case servlet classes were
 * exchanged and multiple ClassLoader namespaces exist.<br><br>
 */
public class Db4oServlet {
	
	/**
	 * single transaction interface.
	 * <br><br>Call this static method to share an ObjectContainer among all sessions.
	 * The ObjectContainer will be closed automatically if all sessions are closed.
	 * @param context the ServletContext
	 * @param session the Session
	 * @param fileName the ObjectContainer file that should be used
	 * @return an ObjectContainer
	 */
    public static ObjectContainer sharedTransaction(
        ServletContext context,
        HttpSession session,
        String fileName) {
        return ServletDaemon.servletDaemon(context, session).objectContainer(session, fileName, true);
    }
    
    
	/**
	 * multi transaction interface.
	 * <br><br>Every session gets it's own transaction.
	 * <br><br>Behind the scenes this method opens an ObjectServer and connects
	 * a client to the server for each session. Clients will be close automatically
	 * upon termination of sessions.
	 * @param context the ServletContext
	 * @param session the Session
	 * @param fileName the ObjectContainer file that should be used
	 * @return an ObjectContainer
	 */
    public static ObjectContainer sessionTransaction(
        ServletContext context,
        HttpSession session,
        String fileName) {
			return ServletDaemon.servletDaemon(context, session).objectContainer(session, fileName, false);
    }
    
    
    /**
	 * closes open db4o sessions for a ServletContext.
	 * <br><br>This method should be called in the <code>destroy()</code>
	 * method of your servlets.<br><br>
	 * It can also be used for maintenance purposes.
     * @param context the ServletContext
     */
    public static void close(ServletContext context){
		ServletDaemon daemon = (ServletDaemon)context.getAttribute(ServletDaemon.ATTRIBUTENAME);
		if(daemon != null){
			daemon.terminate();
		}
    }
}
